import React, { useState, useEffect } from 'react'
// 组件
import { Table, Button, Space, Switch, Modal } from 'antd';
// 图标
import { BarsOutlined } from '@ant-design/icons';
import '../scss/RcDataShow.scss'

import RcAddRules from './components/RcAddRules';
import RcEditRules from './components/RcEditRules'

// 通信
import { useDispatch } from "react-redux";
import { rcDataShowRequest } from '../../../../store/RcManagement/action'
import store from '../../../../store'

// 请求文件
import { changeStateReq, batchDelData, singleDelData } from '../../RcEngine/axiosHttp/index'
// 引入自定义工具类 -- 处理后端返回数据 -- 用于渲染
import { dataProcessing } from '../../RcEngine/tools/index'

// 数据展示组件
function RcDataShow() {

    const [dataShow, setDataShow] = useState([])

    const dispatch = useDispatch()

    store.subscribe(() => {
        setDataShow([
            ...store.getState().rc_manage
        ])
        console.log("获取到最新的数据", store.getState().rc_manage)
    })

    // 定义数据
    const [state, setState] = useState({
        selectedRowKeys: [], // Check here to configure the default column
        loading: false,
    })



    // 通过解构取出 state 中的数据
    const { loading, selectedRowKeys } = state;


    // 定确认删除
    const [visible, setVisible] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [modalText, setModalText] = useState('确认删除吗?');

    // 控制 对话框是否展示
    const showModal = () => {
        setVisible(true);
    };

    const handleOk = (record) => {
        setModalText('正在删除……');
        setConfirmLoading(true);
        delData(record)
        setState({
            selectedRowKeys: [],
            loading: false,
        });
    };

    const handleCancel = () => {
        console.log('Clicked cancel button');
        setVisible(false);
    };



    const handleOkAll = () => {
        setModalText('正在删除……');
        setConfirmLoading(true);
        start(selectedRowKeys)
    };



    // switch 开关事件
    const switchChange = (value) => {
        console.log("switchChange", value)
        const data = {
            id: value.key,
            use_state: !value.stateBtn
        }
        changeStateReq(data)
            .then(res => {
                console.log("changeStateReq -- 成功", res)
                dispatch(
                    rcDataShowRequest()
                )
            })
            .catch(err => {
                console.log("changeStateReq -- 失败", err)
            })
    }

    // 删除 -- 发送 id
    const delData = (record) => {
        console.log("record", record.key)
        singleDelData(record.key)
            .then(res => {
                console.log("单项删除-成功", res)
                setVisible(false);
                setConfirmLoading(false);
                setModalText('确认删除吗?');
                dispatch(
                    rcDataShowRequest()
                )
            })
            .catch(err => {
                console.log("单项删除-失败", err)
            })
    }

    // 表头配置
    const columns = [
        {
            title: '编号',
            dataIndex: 'number',
            key: 'number',
            align: 'center',
            // render: text => <a>{text}</a>,
        },
        {
            title: '规则名称',
            dataIndex: 'name',
            key: 'name',
            align: 'center',
        },
        {
            title: '时间',
            key: 'times',
            dataIndex: 'times',
            align: 'center',
            render: times => (
                <>
                    {times.map(item => {
                        if (item) {

                        }
                        return (
                            <span className={item.slice(0, 3)} key={item.slice(0, 3)}>{item.slice(3)}</span>
                        );
                    })}
                </>
            ),
        },
        {
            title: '上线/下线',
            key: 'stateBtn',
            dataIndex: 'stateBtn',
            align: 'center',
            render: (text, record) => (
                // console.log(record)
                <>
                    <Switch checkedChildren="开启" unCheckedChildren="关闭" defaultChecked={record.stateBtn ? true : false} onChange={() => switchChange(record)} />
                </>
            ),
        },
        {
            title: '命中次数',
            key: 'hit',
            dataIndex: 'hit',
            align: 'center',
        },
        {
            title: '操作',
            key: 'action',
            dataIndex: 'action',
            align: 'center',
            render: (text, record) => (
                // console.log(record)
                <Space size="middle">
                    <RcEditRules msg={record} >查看</RcEditRules>
                    {/* <Button type='dashed' danger onClick={() => delData(record)}>删除</Button> */}
                    <Button type='dashed' danger onClick={showModal}>删除</Button>
                    <Modal
                        title="提示"
                        visible={visible}
                        onOk={() => handleOk(record)}
                        confirmLoading={confirmLoading}
                        onCancel={handleCancel}
                    >
                        <p>{modalText}</p>
                    </Modal>
                </Space>
            ),
        },
    ];

    // 用于存放请求会的数据 --- 处理过后的数据, 可以直接渲染
    const data = [
        {
            key: 1001,
            number: `1001`,
            name: '申请人准入年龄',
            stateBtn: false,
            times: ['sta开始时间: 2021-12-29 16：46', 'due到期时间: 2021-12-31 16：46'],
            hit: '100',
            address: 'London, Park Lane no',
        },
        {
            key: 1002,
            number: `1001`,
            stateBtn: true,
            name: '申请人准入年龄',
            times: ['sta开始时间: 2021-12-29 16：46', 'due到期时间: 2021-12-31 16：46'],
            hit: '100',
            address: 'London, Park Lane no',
        },
        {
            key: 1003,
            number: `1001`,
            stateBtn: false,
            name: '申请人准入年龄',
            times: ['sta开始时间: 2021-12-29 16：46', 'due到期时间: 2021-12-31 16：46'],
            hit: '100',
            address: 'London, Park Lane no',
        },
        {
            key: 1004,
            number: `1001`,
            stateBtn: true,
            name: '申请人准入年龄',
            times: ['sta开始时间: 2021-12-29 16：46', 'due到期时间: 2021-12-31 16：46'],
            hit: '100',
            address: 'London, Park Lane no',
        },
        {
            key: 1005,
            number: `1001`,
            stateBtn: false,
            name: '申请人准入年龄',
            times: ['sta开始时间: 2021-12-29 16：46', 'due到期时间: 2021-12-31 16：46'],
            hit: '100',
            address: 'London, Park Lane no',
        },
        {
            key: 1006,
            number: `1001`,
            stateBtn: true,
            name: '申请人准入年龄',
            times: ['sta开始时间: 2021-12-29 16：46', 'due到期时间: 2021-12-31 16：46'],
            hit: '100',
            address: 'London, Park Lane no',
        },
        {
            key: 1007,
            number: `1001`,
            stateBtn: false,
            name: '申请人准入年龄',
            times: ['sta开始时间: 2021-12-29 16：46', 'due到期时间: 2021-12-31 16：46'],
            hit: '100',
            address: 'London, Park Lane no',
        }
    ];



    // 点击上方的 删除 按钮后执行的操作
    const start = (selectedRowKeys) => {

        console.log("复选框数组", selectedRowKeys)
        // 将页面加载组件开启
        // setState({ ...state, loading: true });

        batchDelData(selectedRowKeys)
            .then(res => {
                console.log("多选删除-成功", res)
                setModalText('确认删除吗?');
                dispatch(
                    rcDataShowRequest()
                )
                setState({
                    selectedRowKeys: [],
                    loading: false,
                });
            })
            .catch(err => {
                console.log("多选删除-失败", err)
                setState({
                    selectedRowKeys: [],
                    loading: false,
                });
            })
    };

    // 复选框
    const onSelectChange = selectedRowKeys => {
        console.log('selectedRowKeys changed - 复选框: ', selectedRowKeys);
        setState({ ...state, selectedRowKeys });
    };


    // 定义对象
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    //
    const hasSelected = selectedRowKeys.length > 0;

    // 分页配置
    const options = {
        // 分页按钮的位置
        position: ['bottomRight'],
        // 每个页面的数据条数
        defaultPageSize: 5,
        // 默认当前页面页数
        defaultCurrent: 1,
        // 当只有一页的时候是否隐藏分页器
        hideOnSinglePage: true,
    }

    useEffect(() => {
        // 发起请求
        // 通过 store 存储数据以及调用
        dispatch(
            rcDataShowRequest()
        )

    }, [])

    return (
        <div className='dataShow'>
            <div className='dataShow-header'>
                <div className='header-left'>
                    <BarsOutlined className='data-icon' />
                    <span>数据列表</span>
                </div>
                <div className='header-right'>
                    <RcAddRules>添加规则</RcAddRules>
                    <Button className='reloadbtn' type="primary" onClick={showModal} disabled={!hasSelected}>
                        删除
                    </Button>
                    <Modal
                        title="提示"
                        visible={visible}
                        onOk={handleOkAll}
                        confirmLoading={confirmLoading}
                        onCancel={handleCancel}
                    >
                        <p>{modalText}</p>
                    </Modal>
                </div>
            </div>
            <Table rowSelection={rowSelection} columns={columns} dataSource={dataShow} bordered pagination={options} />
        </div>
    )
}

export default RcDataShow
